package org.jeecg.modules.cw.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.modules.cw.entity.*;
import org.jeecg.modules.cw.service.*;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.cw.vo.CwZzrygzmxbTjPage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 在职人员工资明细表
 * @Author: jeecg-boot
 * @Date:   2025-09-09
 * @Version: V1.0
 */
@Api(tags="在职人员工资明细表")
@RestController
@RequestMapping("/cw/cwZzrygzmxbTj")
@Slf4j
public class CwZzrygzmxbTjController {
	@Autowired
	private ICwZzrygzmxbTjService cwZzrygzmxbTjService;
	@Autowired
	private ICwZzrygzmxbService cwZzrygzmxbService;
	 @Autowired
	 private ICwApprovalMessageService cwApprovalMessageService;
	 @Autowired
	 private ICwJbszqkzbZhuService cwJbszqkzbZhuService;
	 @Autowired
	 private ICwJbszqkzbService cwJbszqkzbService;
	 @Autowired
	 private ICwAqhjwxjbtService cwAqhjwxjbtService;
	 @Autowired
	 private ISysDepartService sysDepartService;
	 @Autowired
	 private ISysBaseAPI iSysBaseAPI;
	/**
	 * 分页列表查询
	 *
	 * @param cwZzrygzmxbTj
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "在职人员工资明细表-分页列表查询")
	@ApiOperation(value="在职人员工资明细表-分页列表查询", notes="在职人员工资明细表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CwZzrygzmxbTj>> queryPageList(CwZzrygzmxbTj cwZzrygzmxbTj,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<CwZzrygzmxbTj> queryWrapper = QueryGenerator.initQueryWrapper(cwZzrygzmxbTj, req.getParameterMap());
		Page<CwZzrygzmxbTj> page = new Page<CwZzrygzmxbTj>(pageNo, pageSize);
		// 获取登录用户信息
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if (user == null || StringUtils.isEmpty(user.getId())) {
			return Result.error("未获取到登录用户信息，查询失败");
		}
		String currentUserId = user.getId();

		// 获取用户所属部门名称（departName）
		String departIdsByOrgCode = iSysBaseAPI.getDepartIdsByOrgCode(user.getOrgCode());
		SysDepart depart = sysDepartService.getById(departIdsByOrgCode);
		if (depart == null || StringUtils.isEmpty(depart.getDepartName())) {
			return Result.error("未获取到用户所属部门信息，查询失败");
		}
		String departName = depart.getDepartName(); // 用户所属部门名称

		// 定义特权用户ID
		String admin1 = "1985179654538330114";  // 第一个特权用户（拥有待审批权限）
		String admin2 = "1985180799365218306";  // 第二个特权用户
		String admin3 = "1985180919854989314";  // 第三个特权用户
		// 定义需要过滤的部门（机关、鉴定站）
		List<String> allowedDepartments = Arrays.asList("机关", "鉴定站");
		if (admin1.equals(currentUserId)) {
			// 第一个特权用户：
			// 1. 待审批状态仅查询“机关”和“鉴定站”部门
			// 2. 其他状态（通过、驳回、第一人审批同意）无部门限制
			queryWrapper.and(wrapper -> wrapper
					// 待审批 + 限定部门
					.or().eq("state", "待审批").in("unit", allowedDepartments)
					// 其他状态无部门限制
					.or().in("state", "通过", "驳回", "第一人审批同意")
			);
		}else if (admin2.equals(currentUserId) || admin3.equals(currentUserId)) {
			// 第二、三个特权用户：仅可查询通过、驳回
			queryWrapper.in("state", "通过", "驳回","第一人审批同意");
		} else {
			// 非特权用户：仅查询unit等于其所属部门名称的数据
			queryWrapper.eq("unit", departName);
		}
		IPage<CwZzrygzmxbTj> pageList = cwZzrygzmxbTjService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	 /**
	  * 审批
	  * @param id 记录ID
	  * @return 处理结果
	  */
	 @AutoLog(value = "审批-审批")
	 @ApiOperation(value="审批-审批", notes="审批-审批")
	 @RequestMapping(value = "/approval", method = {RequestMethod.PUT, RequestMethod.POST})
	 public Result<String> approval(@RequestParam String id,
									@RequestParam String approvalResult,
									@RequestParam String approvalRemark) {
		 //获取当前用户名
		 LoginUser user= (LoginUser)SecurityUtils.getSubject().getPrincipal();
		 String userId=user.getId();
		 CwZzrygzmxbTj byId = cwZzrygzmxbTjService.getById(id);
		 CwApprovalMessage cwApprovalMessage = new CwApprovalMessage();
		 cwApprovalMessage.setMainId(byId.getId());
		 cwApprovalMessage.setApprovalMessage(approvalRemark);
		 cwApprovalMessage.setApprovalTime(new Date());
		 cwApprovalMessage.setApprover(userId);
		 cwApprovalMessage.setState(approvalResult);
		 cwApprovalMessage.setSpr(user.getRealname());
		 cwApprovalMessageService.save(cwApprovalMessage);
		 if ("通过".equals(approvalResult)) {
			 if ("1985179754371153921".equals(userId)||"1985179977394880513".equals(userId)||
					 "1985180115760775170".equals(userId)||"1985180266818633730".equals(userId)
					 ||"1985180455415513090".equals(userId)){
				 byId.setState("第一人审批同意");
			 }else {
				 byId.setState(approvalResult);
			 }
		 }else {
			 byId.setState(approvalResult);
		 }
		 byId.setApprovalTime(new Date());
		 cwZzrygzmxbTjService.updateById(byId);

		 return Result.OK("提交成功");
	 }

	 /**
	  * 提交处理
	  * @param id 记录ID
	  * @return 处理结果
	  */
	 @AutoLog(value = "提交-提交")
	 @ApiOperation(value="提交-提交", notes="提交-提交")
	 @RequestMapping(value = "/tj", method = {RequestMethod.PUT, RequestMethod.POST})
	 public Result<String> tj(@RequestParam String id) {
		 //获取当前用户名
		 LoginUser user= (LoginUser)SecurityUtils.getSubject().getPrincipal();
		 String userName=user.getRealname();
		 log.info(id);
		 CwZzrygzmxbTj byId = cwZzrygzmxbTjService.getById(id);
		 byId.setState("待审批");
		 cwZzrygzmxbTjService.updateById(byId);
		 return Result.OK("提交成功");
	 }
	/**
	 *   添加
	 *
	 * @param cwZzrygzmxbTjPage
	 * @return
	 */
	@AutoLog(value = "在职人员工资明细表-添加")
	@ApiOperation(value="在职人员工资明细表-添加", notes="在职人员工资明细表-添加")
    //@RequiresPermissions("org.jeecg.modules:cw_zzrygzmxb_tj:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody CwZzrygzmxbTjPage cwZzrygzmxbTjPage) {
		CwZzrygzmxbTj cwZzrygzmxbTj = new CwZzrygzmxbTj();
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		BeanUtils.copyProperties(cwZzrygzmxbTjPage, cwZzrygzmxbTj);
		//获取当前用户名
		String id = user.getId();
		cwZzrygzmxbTj.setMainId(id);

		Double cz=0.0;
		Double fcz=0.0;
		Double czjtbz=0.0;
		Double fczjtbz=0.0;
		Double czjxgz=0.0;
		Double fczjxgz=0.0;
		cwZzrygzmxbTj.setState("待提交");

		String departIdsByOrgCode = iSysBaseAPI.getDepartIdsByOrgCode(user.getOrgCode());
		SysDepart byId = sysDepartService.getById(departIdsByOrgCode);
		String departName = byId.getDepartName();
		cwZzrygzmxbTj.setUnit(departName);
		for (CwZzrygzmxb cwHealthForm : cwZzrygzmxbTjPage.getCwZzrygzmxbList()) {
			cwHealthForm.setUnit(cwZzrygzmxbTj.getUnit());
			cwHealthForm.setYear(cwZzrygzmxbTjPage.getYear());
			cwHealthForm.setUserId(id);
			if (cwHealthForm.getSsx()==null){
				cwHealthForm.setSsx(0.0);
			}
			if (cwHealthForm.getJcjxj()==null){
				cwHealthForm.setJcjxj(0.0);
			}
			if (cwHealthForm.getZzMonth()==null){
				cwHealthForm.setZzMonth(0.0);
			}
			if (cwHealthForm.getNdkhj()==null){
				cwHealthForm.setNdkhj(0.0);
			}
			if (cwHealthForm.getHeatingFee()==null){cwHealthForm.setHeatingFee(0.0);}
			if (cwHealthForm.getHousingSubsidy()==null){cwHealthForm.setHousingSubsidy(0.0);}
			if (cwHealthForm.getHealthSubsidies()==null){cwHealthForm.setHealthSubsidies(0.0);}
			if (cwHealthForm.getJkbybt()==null){cwHealthForm.setJkbybt(0.0);}
			if (cwHealthForm.getHmbt()==null){cwHealthForm.setHmbt(0.0);}
			if (cwHealthForm.getSanitationFee()==null){cwHealthForm.setSanitationFee(0.0);}
			if (cwHealthForm.getWivingAllowance()==null){cwHealthForm.setWivingAllowance(0.0);}
			if (cwHealthForm.getLivingAllowance()==null){cwHealthForm.setLivingAllowance(0.0);}
			if (cwHealthForm.getXjgj()==null){cwHealthForm.setXjgj(0.0);}
			if (cwHealthForm.getPostWage()==null){cwHealthForm.setPostWage(0.0);}
			if (cwHealthForm.getNjtbt()==null){cwHealthForm.setNjtbt(0.0);}
			if (cwHealthForm.getBasePay()==null){cwHealthForm.setBasePay(0.0);}
			if (cwHealthForm.getXjgz()==null){cwHealthForm.setXjgz(0.0);}
			double a = 0.0;
			if(cwHealthForm.getZzyy()==null){
				cwHealthForm.setZzyy(0.0);
			}
			if (cwHealthForm.getZzyy() >= 7.0) {
				a = cwHealthForm.getPostWage() + cwHealthForm.getXjgz();
			} else {
				a = (cwHealthForm.getPostWage() + cwHealthForm.getXjgz()) / 2;
			}

				// 保留两位小数并四舍五入
				a = Math.round(a * 100) / 100.0;


			if ("财政".equals(cwHealthForm.getCzFcz())){
					if ("退休".equals(cwHealthForm.getZzTx())){
						cwHealthForm.setNjxgz(a+(cwHealthForm.getJcjxj()*cwHealthForm.getZzMonth())+cwHealthForm.getNdkhj());
						cwHealthForm.setSsx(a);
						cz+=cwHealthForm.getBasePay();
						czjtbz +=cwHealthForm.getNjtbt();
						czjxgz+=a+(cwHealthForm.getJcjxj()*cwHealthForm.getZzMonth())+cwHealthForm.getNdkhj();
					}else {
						cwHealthForm.setNjxgz(a+(cwHealthForm.getJcjxj()*cwHealthForm.getZzMonth())+cwHealthForm.getNdkhj());
						cwHealthForm.setNjtbt((cwHealthForm.getLivingAllowance()+cwHealthForm.getWivingAllowance()+cwHealthForm.getSanitationFee()+
								cwHealthForm.getHmbt()+cwHealthForm.getJkbybt()+cwHealthForm.getHealthSubsidies()
								+cwHealthForm.getHousingSubsidy())*
								cwHealthForm.getZzMonth()+cwHealthForm.getHeatingFee());
						cwHealthForm.setSsx(a);
						cwHealthForm.setBasePay((cwHealthForm.getPostWage()+cwHealthForm.getXjgj())*cwHealthForm.getZzMonth());
						cz +=(cwHealthForm.getPostWage()+cwHealthForm.getXjgj())*cwHealthForm.getZzMonth();
						czjtbz=(cwHealthForm.getLivingAllowance()+cwHealthForm.getWivingAllowance()+cwHealthForm.getSanitationFee()+
								cwHealthForm.getHmbt()+cwHealthForm.getJkbybt()+cwHealthForm.getHealthSubsidies()
								+cwHealthForm.getHousingSubsidy())*
								cwHealthForm.getZzMonth()+cwHealthForm.getHeatingFee();
						czjxgz+=a+(cwHealthForm.getJcjxj()*cwHealthForm.getZzMonth())+cwHealthForm.getNdkhj();
					}
			}else {
				if ("退休".equals(cwHealthForm.getZzTx())){
					cwHealthForm.setNjxgz(a+(cwHealthForm.getJcjxj()*cwHealthForm.getZzMonth())+cwHealthForm.getNdkhj());
					fcz+=cwHealthForm.getBasePay();
					fczjtbz +=cwHealthForm.getNjtbt();
					cwHealthForm.setYyfhj(new BigDecimal(cwHealthForm.getPostWage()+cwHealthForm.getXjgj()+cwHealthForm.getLivingAllowance()
							+cwHealthForm.getWivingAllowance()+cwHealthForm.getSanitationFee()+cwHealthForm.getHmbt()
							+cwHealthForm.getJkbybt()+cwHealthForm.getHealthSubsidies()+cwHealthForm.getHousingSubsidy()
							+cwHealthForm.getJcjxj()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

					cwHealthForm.setSsx(a);
					fczjxgz+=a+(cwHealthForm.getJcjxj()*cwHealthForm.getZzMonth())+cwHealthForm.getNdkhj();
				}else {
					cwHealthForm.setYyfhj(new BigDecimal(cwHealthForm.getPostWage()+cwHealthForm.getXjgj()+cwHealthForm.getLivingAllowance()
							+cwHealthForm.getWivingAllowance()+cwHealthForm.getSanitationFee()+cwHealthForm.getHmbt()
							+cwHealthForm.getJkbybt()+cwHealthForm.getHealthSubsidies()+cwHealthForm.getHousingSubsidy()
							+cwHealthForm.getJcjxj()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

					cwHealthForm.setNjxgz(a+(cwHealthForm.getJcjxj()*cwHealthForm.getZzMonth())+cwHealthForm.getNdkhj());
					cwHealthForm.setNjtbt((cwHealthForm.getLivingAllowance()+cwHealthForm.getWivingAllowance()+cwHealthForm.getSanitationFee()+
							cwHealthForm.getHmbt()+cwHealthForm.getJkbybt()+cwHealthForm.getHealthSubsidies()
							+cwHealthForm.getHousingSubsidy())*
							cwHealthForm.getZzMonth()+cwHealthForm.getHeatingFee());
					cwHealthForm.setSsx(a);
					cwHealthForm.setBasePay((cwHealthForm.getPostWage()+cwHealthForm.getXjgj())*cwHealthForm.getZzMonth());
					fcz +=(cwHealthForm.getPostWage()+cwHealthForm.getXjgj())*cwHealthForm.getZzMonth();
					fczjtbz=(cwHealthForm.getLivingAllowance()+cwHealthForm.getWivingAllowance()+cwHealthForm.getSanitationFee()+
							cwHealthForm.getHmbt()+cwHealthForm.getJkbybt()
							+cwHealthForm.getHealthSubsidies()+cwHealthForm.getHousingSubsidy())*
							cwHealthForm.getZzMonth()+cwHealthForm.getHeatingFee();
					fczjxgz+=a+(cwHealthForm.getJcjxj()*cwHealthForm.getZzMonth())+cwHealthForm.getNdkhj();
				}
			}
		}
		cwZzrygzmxbTjService.saveMain(cwZzrygzmxbTj, cwZzrygzmxbTjPage.getCwZzrygzmxbList());
		return Result.OK("添加成功！");
	}

	 /**
	 *  编辑
	 *
	 * @param cwZzrygzmxbTjPage
	 * @return
	 */
	@AutoLog(value = "在职人员工资明细表-编辑")
	@ApiOperation(value="在职人员工资明细表-编辑", notes="在职人员工资明细表-编辑")
    //@RequiresPermissions("org.jeecg.modules:cw_zzrygzmxb_tj:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody CwZzrygzmxbTjPage cwZzrygzmxbTjPage) {
		CwZzrygzmxbTj cwZzrygzmxbTj = new CwZzrygzmxbTj();
		BeanUtils.copyProperties(cwZzrygzmxbTjPage, cwZzrygzmxbTj);
		CwZzrygzmxbTj cwZzrygzmxbTjEntity = cwZzrygzmxbTjService.getById(cwZzrygzmxbTj.getId());
		if(cwZzrygzmxbTjEntity==null) {
			return Result.error("未找到对应数据");
		}

		Double cz=0.0;
		Double fcz=0.0;
		Double czjtbz=0.0;
		Double fczjtbz=0.0;
		Double czjxgz=0.0;
		Double fczjxgz=0.0;
		LoginUser user = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		String id = user.getId();
		LambdaQueryWrapper<CwAqhjwxjbt> wrapper1 = new LambdaQueryWrapper<>();
		wrapper1.eq(CwAqhjwxjbt::getUserId,user.getId())
				.eq(CwAqhjwxjbt::getYear,cwZzrygzmxbTjPage.getYear());
		//安全财政
		Double anquancz=0.0;
		Double anquanfcz=0.0;
		Double weixiucz=0.0;
		Double weixiufcz=0.0;
		for (CwAqhjwxjbt cwAqhjwxjbt : cwAqhjwxjbtService.list(wrapper1)) {
			String aqWx = cwAqhjwxjbt.getAqWx();
			if ("安全".equals(aqWx)){
					if ("财政".equals(cwAqhjwxjbt.getCzFcz())){
						if (cwAqhjwxjbt.getMoney()==null){
							cwAqhjwxjbt.setMoney(0.0);
						}
						anquancz+=cwAqhjwxjbt.getMoney();
					}else {
						if (cwAqhjwxjbt.getMoney()==null){
							cwAqhjwxjbt.setMoney(0.0);
						}
						anquanfcz+=cwAqhjwxjbt.getMoney();
					}
			}else {
				if ("财政".equals(cwAqhjwxjbt.getCzFcz())){
					if (cwAqhjwxjbt.getMoney()==null){
						cwAqhjwxjbt.setMoney(0.0);
					}
					weixiucz+=cwAqhjwxjbt.getMoney();
				}else {
					if (cwAqhjwxjbt.getMoney()==null){
						cwAqhjwxjbt.setMoney(0.0);
					}
					weixiufcz+=cwAqhjwxjbt.getMoney();
				}
			}
		}

		for (CwZzrygzmxb cwHealthForm : cwZzrygzmxbTjPage.getCwZzrygzmxbList()) {
			cwHealthForm.setUnit(cwZzrygzmxbTjPage.getUnit());
			cwHealthForm.setYear(cwZzrygzmxbTjPage.getYear());
			cwHealthForm.setUserId(id);
			if (cwHealthForm.getSsx()==null){
				cwHealthForm.setSsx(0.0);
			}
			if (cwHealthForm.getJcjxj()==null){
				cwHealthForm.setJcjxj(0.0);
			}
			if (cwHealthForm.getZzMonth()==null){
				cwHealthForm.setZzMonth(0.0);
			}
			if (cwHealthForm.getNdkhj()==null){
				cwHealthForm.setNdkhj(0.0);
			}
			if (cwHealthForm.getHeatingFee()==null){cwHealthForm.setHeatingFee(0.0);}
			if (cwHealthForm.getHousingSubsidy()==null){cwHealthForm.setHousingSubsidy(0.0);}
			if (cwHealthForm.getHealthSubsidies()==null){cwHealthForm.setHealthSubsidies(0.0);}
			if (cwHealthForm.getJkbybt()==null){cwHealthForm.setJkbybt(0.0);}
			if (cwHealthForm.getHmbt()==null){cwHealthForm.setHmbt(0.0);}
			if (cwHealthForm.getSanitationFee()==null){cwHealthForm.setSanitationFee(0.0);}
			if (cwHealthForm.getWivingAllowance()==null){cwHealthForm.setWivingAllowance(0.0);}
			if (cwHealthForm.getLivingAllowance()==null){cwHealthForm.setLivingAllowance(0.0);}
			if (cwHealthForm.getXjgj()==null){cwHealthForm.setXjgj(0.0);}
			if (cwHealthForm.getPostWage()==null){cwHealthForm.setPostWage(0.0);}
			if (cwHealthForm.getNjtbt()==null){cwHealthForm.setNjtbt(0.0);}
			if (cwHealthForm.getBasePay()==null){cwHealthForm.setBasePay(0.0);}
			if (cwHealthForm.getXjgz()==null){cwHealthForm.setXjgz(0.0);}
			double a = 0.0;
			if (cwHealthForm.getZzyy()==null){
				cwHealthForm.setZzyy(0.0);
			}
			if (cwHealthForm.getZzyy() >= 7.0) {
				a = cwHealthForm.getPostWage() + cwHealthForm.getXjgz();
			} else {
				a = (cwHealthForm.getPostWage() + cwHealthForm.getXjgz()) / 2;
			}
// 保留两位小数并四舍五入
			a = Math.round(a * 100) / 100.0;

			if ("财政".equals(cwHealthForm.getCzFcz())){
				if ("退休".equals(cwHealthForm.getZzTx())){
					cwHealthForm.setNjxgz(a+cwHealthForm.getJcjxj()*cwHealthForm.getZzMonth()+cwHealthForm.getNdkhj());
					cz+=cwHealthForm.getBasePay();
					czjtbz +=cwHealthForm.getNjtbt();
					cwHealthForm.setSsx(a);
					czjxgz+=a+cwHealthForm.getJcjxj()*cwHealthForm.getZzMonth()+cwHealthForm.getNdkhj();
				}else {
					cwHealthForm.setNjxgz(a+cwHealthForm.getJcjxj()*cwHealthForm.getZzMonth()+cwHealthForm.getNdkhj());
					cwHealthForm.setNjtbt((cwHealthForm.getLivingAllowance()+cwHealthForm.getWivingAllowance()+cwHealthForm.getSanitationFee()+
							cwHealthForm.getHmbt()+cwHealthForm.getJkbybt()+cwHealthForm.getHealthSubsidies()
							+cwHealthForm.getHousingSubsidy())*
							cwHealthForm.getZzMonth()+cwHealthForm.getHeatingFee());
					cwHealthForm.setSsx(a);
					cwHealthForm.setBasePay((cwHealthForm.getPostWage()+cwHealthForm.getXjgj())*cwHealthForm.getZzMonth());
					cz +=(cwHealthForm.getPostWage()+cwHealthForm.getXjgj())*cwHealthForm.getZzMonth();
					czjtbz=(cwHealthForm.getLivingAllowance()+cwHealthForm.getWivingAllowance()+cwHealthForm.getSanitationFee()+
							cwHealthForm.getHmbt()+cwHealthForm.getJkbybt()+cwHealthForm.getHealthSubsidies()
							+cwHealthForm.getHousingSubsidy())*
							cwHealthForm.getZzMonth()+cwHealthForm.getHeatingFee();
					czjxgz+=a+cwHealthForm.getJcjxj()*cwHealthForm.getZzMonth()+cwHealthForm.getNdkhj();
				}
			}else {
				if ("退休".equals(cwHealthForm.getZzTx())){
					cwHealthForm.setNjxgz(a+cwHealthForm.getJcjxj()*cwHealthForm.getZzMonth()+cwHealthForm.getNdkhj());
					fcz+=cwHealthForm.getBasePay();
					fczjtbz +=cwHealthForm.getNjtbt();
					cwHealthForm.setSsx(a);
					cwHealthForm.setYyfhj(new BigDecimal(cwHealthForm.getPostWage()+cwHealthForm.getXjgj()+cwHealthForm.getLivingAllowance()
							+cwHealthForm.getWivingAllowance()+cwHealthForm.getSanitationFee()+cwHealthForm.getHmbt()
							+cwHealthForm.getJkbybt()+cwHealthForm.getHealthSubsidies()+cwHealthForm.getHousingSubsidy()
							+cwHealthForm.getJcjxj()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

					fczjxgz+=a+cwHealthForm.getJcjxj()*cwHealthForm.getZzMonth()+cwHealthForm.getNdkhj();
				}else {
					cwHealthForm.setNjxgz(a+cwHealthForm.getJcjxj()*cwHealthForm.getZzMonth()+cwHealthForm.getNdkhj());
					cwHealthForm.setNjtbt((cwHealthForm.getLivingAllowance()+cwHealthForm.getWivingAllowance()+cwHealthForm.getSanitationFee()+
							cwHealthForm.getHmbt()+cwHealthForm.getJkbybt()+cwHealthForm.getHealthSubsidies()
							+cwHealthForm.getHousingSubsidy())*
							cwHealthForm.getZzMonth()+cwHealthForm.getHeatingFee());
					cwHealthForm.setSsx(a);
					cwHealthForm.setYyfhj(new BigDecimal(cwHealthForm.getPostWage()+cwHealthForm.getXjgj()+cwHealthForm.getLivingAllowance()
							+cwHealthForm.getWivingAllowance()+cwHealthForm.getSanitationFee()+cwHealthForm.getHmbt()
							+cwHealthForm.getJkbybt()+cwHealthForm.getHealthSubsidies()+cwHealthForm.getHousingSubsidy()
							+cwHealthForm.getJcjxj()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

					cwHealthForm.setBasePay((cwHealthForm.getPostWage()+cwHealthForm.getXjgj())*cwHealthForm.getZzMonth());
					fcz +=(cwHealthForm.getPostWage()+cwHealthForm.getXjgj())*cwHealthForm.getZzMonth();
					fczjtbz=(cwHealthForm.getLivingAllowance()+cwHealthForm.getWivingAllowance()+cwHealthForm.getSanitationFee()+
							cwHealthForm.getHmbt()+cwHealthForm.getJkbybt()
							+cwHealthForm.getHealthSubsidies()+cwHealthForm.getHousingSubsidy())*
							cwHealthForm.getZzMonth()+cwHealthForm.getHeatingFee();
					fczjxgz+=a+cwHealthForm.getJcjxj()*cwHealthForm.getZzMonth()+cwHealthForm.getNdkhj();
				}
			}
		}

		cwZzrygzmxbTjService.updateMain(cwZzrygzmxbTj, cwZzrygzmxbTjPage.getCwZzrygzmxbList());
//		LambdaQueryWrapper<CwJbszqkzb> wrapper = new LambdaQueryWrapper<>();
//		wrapper.eq(CwJbszqkzb::getYear,cwZzrygzmxbTjPage.getYear())
//				.eq(CwJbszqkzb::getUnit,cwZzrygzmxbTj.getUnit())
//				.in(CwJbszqkzb::getProject,"基本工资","绩效工资","津贴补贴");
//		for (CwJbszqkzb cwJbszqkzb : cwJbszqkzbService.list(wrapper)) {
//			if ("基本工资".equals(cwJbszqkzb.getProject())) {
//				cwJbszqkzb.setUnit(cwZzrygzmxbTj.getUnit());
//				cwJbszqkzb.setYear(cwZzrygzmxbTjPage.getYear());
//				cwJbszqkzb.setFinancial(cz);
//				cwJbszqkzb.setNonFinancials(fcz);
//				if (cwJbszqkzb.getYsshj()==null){
//					cwJbszqkzb.setYsshj(0.0);
//				}
//				cwJbszqkzb.setYsshj(cz+fcz);
//				cwJbszqkzb.setCwPx(12);
//				cwJbszqkzbService.updateById(cwJbszqkzb);
//			}
//			if ("绩效工资".equals(cwJbszqkzb.getProject())){
//				cwJbszqkzb.setUnit(cwZzrygzmxbTj.getUnit());
//				cwJbszqkzb.setYear(cwZzrygzmxbTjPage.getYear());
//				cwJbszqkzb.setFinancial(czjxgz+anquancz);
//				cwJbszqkzb.setNonFinancials(fczjxgz+anquanfcz);
//				if (cwJbszqkzb.getYsshj()==null){
//					cwJbszqkzb.setYsshj(0.0);
//				}
//				cwJbszqkzb.setYsshj(czjxgz+fczjxgz+anquancz+anquanfcz);
//				cwJbszqkzb.setCwPx(16);
//				cwJbszqkzbService.updateById(cwJbszqkzb);
//			}
//			if ("津贴补贴".equals(cwJbszqkzb.getProject())){
//				cwJbszqkzb.setUnit(cwZzrygzmxbTj.getUnit());
//				cwJbszqkzb.setYear(cwZzrygzmxbTjPage.getYear());
//				cwJbszqkzb.setFinancial(czjtbz+weixiucz);
//				cwJbszqkzb.setNonFinancials(fczjtbz+weixiufcz);
//				if (cwJbszqkzb.getYsshj()==null){
//					cwJbszqkzb.setYsshj(0.0);
//				}
//				cwJbszqkzb.setYsshj(czjtbz+weixiucz+fczjtbz+weixiufcz);
//				cwJbszqkzb.setCwPx(13);
//				cwJbszqkzbService.updateById(cwJbszqkzb);
//			}
//		}

		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "在职人员工资明细表-通过id删除")
	@ApiOperation(value="在职人员工资明细表-通过id删除", notes="在职人员工资明细表-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:cw_zzrygzmxb_tj:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		cwZzrygzmxbTjService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "在职人员工资明细表-批量删除")
	@ApiOperation(value="在职人员工资明细表-批量删除", notes="在职人员工资明细表-批量删除")
    //@RequiresPermissions("org.jeecg.modules:cw_zzrygzmxb_tj:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.cwZzrygzmxbTjService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "在职人员工资明细表-通过id查询")
	@ApiOperation(value="在职人员工资明细表-通过id查询", notes="在职人员工资明细表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CwZzrygzmxbTj> queryById(@RequestParam(name="id",required=true) String id) {
		CwZzrygzmxbTj cwZzrygzmxbTj = cwZzrygzmxbTjService.getById(id);
		if(cwZzrygzmxbTj==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(cwZzrygzmxbTj);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "在职人员工资明细表-通过主表ID查询")
	@ApiOperation(value="在职人员工资明细表-通过主表ID查询", notes="在职人员工资明细表-通过主表ID查询")
	@GetMapping(value = "/queryCwZzrygzmxbByMainId")
	public Result<IPage<CwZzrygzmxb>> queryCwZzrygzmxbListByMainId(@RequestParam(name="id",required=true) String id) {
		List<CwZzrygzmxb> cwZzrygzmxbList = cwZzrygzmxbService.selectByMainId(id);
		IPage <CwZzrygzmxb> page = new Page<>();
		page.setRecords(cwZzrygzmxbList);
		page.setTotal(cwZzrygzmxbList.size());
		return Result.OK(page);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param cwZzrygzmxbTj
    */
    //@RequiresPermissions("org.jeecg.modules:cw_zzrygzmxb_tj:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CwZzrygzmxbTj cwZzrygzmxbTj) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<CwZzrygzmxbTj> queryWrapper = QueryGenerator.initQueryWrapper(cwZzrygzmxbTj, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

     //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
           List<String> selectionList = Arrays.asList(selections.split(","));
           queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<CwZzrygzmxbTj>  cwZzrygzmxbTjList = cwZzrygzmxbTjService.list(queryWrapper);

      // Step.3 组装pageList
      List<CwZzrygzmxbTjPage> pageList = new ArrayList<CwZzrygzmxbTjPage>();
      for (CwZzrygzmxbTj main : cwZzrygzmxbTjList) {
          CwZzrygzmxbTjPage vo = new CwZzrygzmxbTjPage();
          BeanUtils.copyProperties(main, vo);
          List<CwZzrygzmxb> cwZzrygzmxbList = cwZzrygzmxbService.selectByMainId(main.getId());
          vo.setCwZzrygzmxbList(cwZzrygzmxbList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "在职人员工资明细表列表");
      mv.addObject(NormalExcelConstants.CLASS, CwZzrygzmxbTjPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("在职人员工资明细表数据", "导出人:"+sysUser.getRealname(), "在职人员工资明细表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("org.jeecg.modules:cw_zzrygzmxb_tj:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<CwZzrygzmxbTjPage> list = ExcelImportUtil.importExcel(file.getInputStream(), CwZzrygzmxbTjPage.class, params);
              for (CwZzrygzmxbTjPage page : list) {
                  CwZzrygzmxbTj po = new CwZzrygzmxbTj();
                  BeanUtils.copyProperties(page, po);
                  cwZzrygzmxbTjService.saveMain(po, page.getCwZzrygzmxbList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
